import React, { useMemo, useRef } from 'react';
import Info from './Info';

const JerseyComponent = ({ text = "35.3bar", number = 5, rotation = 0 }) => {
  return (
    <div
      className="relative rounded-lg w-16 h-20"
      style={{ transform: `rotate(${rotation}deg)` }}
    >
      {/* 球衣主体 */}
      <div className="p-1 text-center h-full flex flex-col justify-center">
        {/* 号码 */}
        <div className="text-[5px] font-bold text-gray-800">{number}</div>

        {/* 两个圆形装饰 */}
        <div className="flex justify-center">
          <div className="w-2 h-2 bg-pink-400 rounded-full"></div>
          <div className="w-2 h-2 bg-pink-400 rounded-full"></div>
        </div>

        {/* 文字 - smaller font and tighter spacing */}
        <div className="text-[7px] text-gray-600 leading-tight">{text}</div>

        {/* 底部竖条 - longer and narrower */}
        <div className="mx-auto w-1 h-8 bg-pink-400 rounded"></div>
      </div>
    </div>
  );
};


const CircularJerseyLayout = ({ containerRef }: { containerRef: React.RefObject<HTMLDivElement> }) => {
  const [containerSize, setContainerSize] = React.useState({ width: 0, height: 0 });

  const jerseyData = [
    { number: 1, text: "32.1bar" },
    { number: 2, text: "28.5bar" },
    { number: 3, text: "41.2bar" },
    { number: 4, text: "35.8bar" },
    { number: 5, text: "29.3bar" },
    { number: 6, text: "38.7bar" },
    { number: 7, text: "33.4bar" },
    { number: 8, text: "42.1bar" },
    { number: 9, text: "31.6bar" },
    { number: 10, text: "36.9bar" },
    { number: 11, text: "27.8bar" },
    { number: 12, text: "39.5bar" },
    { number: 13, text: "34.2bar" },
    { number: 14, text: "40.3bar" },
    { number: 15, text: "30.7bar" },
    { number: 16, text: "37.4bar" },
    { number: 17, text: "35.3bar" }
  ];

  // 监听容器大小变化
  React.useEffect(() => {
    const updateSize = () => {
      if (containerRef?.current) {
        const { width, height } = containerRef.current.getBoundingClientRect();
        setContainerSize({ width, height });
      }
    };

    updateSize();
    window.addEventListener('resize', updateSize);

    let resizeObserver: ResizeObserver | null = null;
    if (containerRef?.current) {
      resizeObserver = new ResizeObserver(updateSize);
      resizeObserver.observe(containerRef.current);
    }

    return () => {
      window.removeEventListener('resize', updateSize);
      if (resizeObserver) {
        resizeObserver.disconnect();
      }
    };
  }, [containerRef]);

  // 计算相对尺寸
  const minDimension = Math.min(containerSize.width, containerSize.height);
  const radius = minDimension * 0.4; // 使用相对半径
  const centerX = containerSize.width / 2;
  const centerY = containerSize.height / 2;

  // 计算球衣中心点形成的圆环
  const jerseyCenterPoints = jerseyData.map((_, index) => {
    const angle = (index * 360) / 17;
    const radian = (angle * Math.PI) / 180;
    return {
      x: centerX + radius * Math.cos(radian - Math.PI / 2),
      y: centerY + radius * Math.sin(radian - Math.PI / 2)
    };
  });

  // 计算球衣中心点形成的圆环的圆心
  let sumX = 0, sumY = 0;
  jerseyCenterPoints.forEach(point => {
    sumX += point.x;
    sumY += point.y;
  });
  const jerseyCircleCenterX = sumX / jerseyCenterPoints.length;
  const jerseyCircleCenterY = sumY / jerseyCenterPoints.length;

  // 使用球衣中心点形成的圆心
  const visualCenterX = jerseyCircleCenterX;
  const visualCenterY = jerseyCircleCenterY;

  // Define jersey groups with colors
  const jerseyGroups = {
    red: [1, 2, 3],
    blue: [4, 5, 6, 7],
    yellow: [8, 9, 10, 11, 12],
    pink: [13, 14, 15, 16, 17]
  };

  // Color mapping
  const groupColors = {
    red: '#FF6B6B',
    blue: '#54A0FF',
    yellow: '#FECA57',
    pink: '#FF9FF3'
  };

  // Generate arcs for each group
  const generateArcs = () => {
    const arcs = [];
    const angleStep = 360 / 17;
    
    for (const [groupName, numbers] of Object.entries(jerseyGroups)) {
      const indices = numbers.map(num => num - 1);
      const minIndex = Math.min(...indices);
      const maxIndex = Math.max(...indices);
      
      const startAngle = (minIndex - 0.5) * angleStep;
      const endAngle = (maxIndex + 0.5) * angleStep;
      
      arcs.push({
        color: groupColors[groupName as keyof typeof groupColors],
        startAngle: startAngle - 90, // Adjust for top position
        endAngle: endAngle - 90,     // Adjust for top position
        innerRadius: radius * 0.7,
        outerRadius: radius * 0.75
      });
    }
    
    return arcs;
  };

  const arcs = generateArcs();

  // Function to describe arc path
  const describeArc = (x: number, y: number, innerRadius: number, outerRadius: number, startAngle: number, endAngle: number) => {
    const startRad = (startAngle * Math.PI) / 180;
    const endRad = (endAngle * Math.PI) / 180;
    
    const innerStart = {
      x: x + innerRadius * Math.cos(startRad),
      y: y + innerRadius * Math.sin(startRad)
    };
    
    const outerStart = {
      x: x + outerRadius * Math.cos(startRad),
      y: y + outerRadius * Math.sin(startRad)
    };
    
    const outerEnd = {
      x: x + outerRadius * Math.cos(endRad),
      y: y + outerRadius * Math.sin(endRad)
    };
    
    const innerEnd = {
      x: x + innerRadius * Math.cos(endRad),
      y: y + innerRadius * Math.sin(endRad)
    };
    
    const largeArc = endAngle - startAngle <= 180 ? 0 : 1;
    
    return `
      M ${innerStart.x} ${innerStart.y}
      L ${outerStart.x} ${outerStart.y}
      A ${outerRadius} ${outerRadius} 0 ${largeArc} 1 ${outerEnd.x} ${outerEnd.y}
      L ${innerEnd.x} ${innerEnd.y}
      A ${innerRadius} ${innerRadius} 0 ${largeArc} 0 ${innerStart.x} ${innerStart.y}
      Z
    `;
  };

  return (
    <div className="relative w-full h-full flex items-center justify-center">
      {/* Arc visualization */}
      <div
        className="absolute rounded-full"
        style={{
          width: `${radius * 1.5}px`,
          height: `${radius * 1.5}px`,
          left: `${visualCenterX - radius * 0.75}px`,
          top: `${visualCenterY - radius * 0.75}px`,
          border: '1px solid transparent',
        }}
      >
        <svg
          width="100%"
          height="100%"
          viewBox={`0 0 ${radius * 1.5} ${radius * 1.5}`}
          style={{ position: 'absolute', top: 0, left: 0 }}
        >
          {arcs.map((arc, index) => (
            <path
              key={index}
              d={describeArc(
                radius * 0.75,
                radius * 0.75,
                arc.innerRadius,
                arc.outerRadius,
                arc.startAngle,
                arc.endAngle
              )}
              fill={arc.color}
              opacity="0.7"
            />
          ))}
        </svg>

        {/* 内部透明圆形 */}
        <div
          className="absolute bg-amber-50 rounded-full"
          style={{
            width: `${radius * 1.4}px`,
            height: `${radius * 1.4}px`,
            left: '50%',
            top: '50%',
            transform: 'translate(-50%, -50%)',
          }}
        >
          {/* 第一个虚线圆环 */}
          <div
            className="absolute rounded-full border-dashed border-gray-400"
            style={{
              width: `${radius * 1.35}px`,
              height: `${radius * 1.35}px`,
              left: '50%',
              top: '50%',
              transform: 'translate(-50%, -50%)',
              borderWidth: '1px',
            }}
          >
            {/* 第二个虚线圆环 */}
            <div
              className="absolute rounded-full border-dashed border-gray-500"
              style={{
                width: `${radius * 1.2}px`,
                height: `${radius * 1.2}px`,
                left: '50%',
                top: '50%',
                transform: 'translate(-50%, -50%)',
                borderWidth: '1px',
              }}
            >
              {/* 拼装状态组件 */}
              <Info />
            </div>

            {/* 在颜色组交界处画虚线连接线 */}
            {(() => {
              // 计算每个颜色组之间的交界角度
              const angleStep = 360 / 17;
              const boundaries = [
                { from: 'red', to: 'blue', position: 3.5 },      // red和blue之间
                { from: 'blue', to: 'yellow', position: 7.5 },    // blue和yellow之间
                { from: 'yellow', to: 'pink', position: 12.5 },   // yellow和pink之间
                { from: 'pink', to: 'red', position: 17.5 }       // pink和red之间（回到起点）
              ];
              
              return boundaries.map((boundary, index) => {
                // 计算交界处的角度（减90度是因为起始点在顶部）
                const angle = (boundary.position - 1) * angleStep - 90;
                const radian = (angle * Math.PI) / 180;
                const innerRadius = radius * 0.6;
                const outerRadius = radius * 0.675;

                const x1 = innerRadius * Math.cos(radian);
                const y1 = innerRadius * Math.sin(radian);

                const lineLength = outerRadius - innerRadius;
                const lineAngle = angle;

                return (
                  <div
                    key={index}
                    className="absolute border-t border-dashed border-gray-500"
                    style={{
                      width: `${lineLength}px`,
                      left: '50%',
                      top: '50%',
                      transformOrigin: '0 0',
                      transform: `translate(${x1}px, ${y1}px) rotate(${lineAngle}deg)`,
                      borderWidth: '1.5px',
                    }}
                  ></div>
                );
              });
            })()}
          </div>
        </div>
      </div>

      {/* 17个球衣组件围成圆圈 */}
      {jerseyData.map((jersey, index) => {
        const angle = (index * 360) / 17;
        const radian = (angle * Math.PI) / 180;
        
        // 使用计算出的球衣中心点
        const x = jerseyCenterPoints[index].x;
        const y = jerseyCenterPoints[index].y;
        
        const rotationAngle = angle + 180;
        return (
          <div
            key={index}
            className="absolute transform -translate-x-1/2 -translate-y-1/2"
            style={{
              left: `${x}px`,
              top: `${y}px`,
            }}
          >
            <JerseyComponent
              number={jersey.number}
              text={jersey.text}
              rotation={rotationAngle}
            />
          </div>
        );
      })}
    </div>
  );
};

export default CircularJerseyLayout;